package 求进入环的第一个节点;

import java.util.HashMap;
import java.util.Map;

public class jishengjun {

    public static void main(String[] args) {
        Node result=calc(getTestNode());
        System.out.println(result==null?"没有环":result.toString());
    }

    private static Node calc(Node first) {
        Map<Integer, Node> map = new HashMap<>();
        Node current = first;
        while (current != null) {
            if (map.get(current.hashCode()) == null) {
                map.put(current.hashCode(), current);
            } else {
                return current;
            }
            current=current.next;
        }
        return null;
    }


    private static Node getTestNode() {
        Node node1 = new Node("1");
        Node node2 = new Node("2");
        Node node3 = new Node("3");
        Node node4 = new Node("4");
        Node node5 = new Node("5");
        Node node6 = new Node("6");
        Node node7 = new Node("7");
        Node node8 = new Node("8");
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;

        return node1;
    }

    static class Node {
        String data;
        Node next;

        public Node(String data) {
            this.data = data;
        }

        boolean isLast() {
            return next == null;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "data='" + data + '\'' +
                    '}';
        }
    }
}
